<?php
 namespace app\models;
 
 use app\models\BaseModel;
 use app\enum\EnumOther;
 use app\dao\TransferDAO;
 use app\dao\TransferDetailDAO;
 use Yii;
 use app\enum\EnumOriginType;
 use app\dao\ProductDAO;
 use app\dao\WarehouseDAO;
 use app\dao\TransactionDAO;
 use app\helpers\Utility;
 use app\dao\ProductUpdateLogDAO;
 use app\dao\StockPileDAO;
use app\dao\PriceTransactionDAO;
					 
 class TransferModel extends BaseModel
 {
 	/**
 	 * @desc 覆盖父方法返回对象
 	 * @author liaojianwen
 	 * @date 2017-03-31
 	 * @return TransferModel
 	 */
 	public static function model($className=__CLASS__)
 	{
 		return parent::model($className);
 	}
 	
 	/**
 	 * @desc 保存调拨单
 	 * @author liaojianwen
 	 * @date 2017-04-01
 	 */
 	public function saveTransfer ( $head, $detail, $remove, $id )
 	{
 		if(empty($head)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
 		}
 		if (empty ( $detail )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
 		}
 		//清掉为空的元素
 		foreach ($head as $k =>$hed){
 			if(empty($hed)){
 				unset($head[$k]);
 			}
 		}
 		foreach ($detail as $k=> $det){
 			foreach ($det as $j => $deet){
 				if(empty($deet)){
 					unset($detail[$k][$j]);
 				}
 			}
 		}
 		// 表头信息
 		$tr = Yii::$app->db->beginTransaction();
 		try{
 			$head ['transfer_date'] = strtotime ( $head ['transfer_date'] );
 			$cond_head = "transfer_id =:id";
 			$param_head = [
 					':id' => $id
 			];
 			//  			$Iid = 1;
 			$Iid = TransferDAO::getInstance ()->ireplaceinto ( $head, $cond_head, $param_head, true );
 			if (! $Iid) {
 				$tr->rollBack();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transfer_head failure' );
 			}
 			//删除的明细
 			foreach ($remove as $move){
 				$res_remove = TransferDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "transfer_det_id = :det_id", [':det_id'=>$move['transfer_det_id']]);
 				if(!$res_remove){
 					$tr->rollBack();
 					$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove transfer_dat_id:'+$move['transfer_det_id'] +'failed');
 				}
 			}
 			foreach ( $detail as &$det ) {
 				$det ['transfer_id'] = $Iid;
 				$det ['delete_flag'] = EnumOther::NO_DELETE;
 				$cond_det = "transfer_id = :id and transfer_det_id = :lid";
 				$param_det = [
 						':id' => $Iid,
 						':lid' => isset($det ['transfer_det_id'])?$det['transfer_det_id']:0,
 				];
 				
 				//添加 成本 --start
 				$PRODUCT = ProductDAO::getInstance()->iselect("price", "product_id =:pid", [':pid' => $det['product_id']],'one');
 				if(empty($PRODUCT)){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product is null');
 				}
 				$det['cost_price'] = $PRODUCT['price'];
 				$det['cost_amount'] = round(($PRODUCT['price'] * $det['quantity']),2);
 				//---end
 				
 				$res_det = TransferDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
 				if (! $res_det) {
 					$tr->rollBack();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transfer_detail failure' );
 				}
 			}
 			$tr->commit();
 			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
 		}catch (\Exception $e){
 			$tr->rollBack();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 获取调拨单列表数据
 	 * @author liaojianwen
 	 * @date 2017-04-01
 	 */
 	public function getTransfers ( $pageInfo, $condition, $filter)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = TransferDAO::getInstance()->getTransfers($condition, $filter, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 编辑页面调拨单数据
 	 * @author liaojianwen
 	 * @date 2017-04-01
 	 */
 	public function getTransferInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$in_head = TransferDAO::getInstance()->getTransferHead($id);
 		if(empty($in_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$in_det = TransferDetailDAO::getInstance()->getTransferDetail($id);
 		if(empty($in_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		$result['head'] = $in_head;
 		$result['det'] = $in_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 确认调拨单
 	 * @author liaojianwen
 	 * @date 2017-04-01
 	 */
 	public function confirmTransfer($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$id = (int)$id;
 		$tr = Yii::$app->db->beginTransaction ();
 		try {
 			$re_confirm = TransferDAO::getInstance ()->updateByPk ( $id, [
 					'confirm_flag' => EnumOther::CONFIRM
 			] );
 			if (! $re_confirm) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'confirm fail' );
 			}
 			$fields = [
 					'h.transfer_no',
 					'h.transfer_id',
 					'd.product_id',
 					'd.quantity',
 					'd.transfer_det_id',
 					'h.warehouse_out',
 					'h.warehouse_in',
 					'h.transfer_date',
 					'h.transfer_type',
 					'd.quantity_unit',
 					'd.base_quantity',
 					'd.base_unit',
 					'w.warehouse_name as warehouse_in_name',
 					'd.cost_price',
 					'd.cost_amount',
 					'd.base_price',
 					'd.amount',
 			];
 			$conditions = "d.transfer_id =:id and d.delete_flag = :flag";
 			$params = [
 					':id' => $id,
 					':flag' => EnumOther::NO_DELETE
 			];
 			$joinArray = [
 					[
 							'transfer h',
 							"h.transfer_id = d.transfer_id"
 					],
 					[
 						'warehouse w',
 						'w.warehouse_id = h.warehouse_in',
 					]
 			];
 			$transfer_det = TransferDetailDAO::getInstance ()->iselect ( $fields, $conditions, $params, 'all', 'd.transfer_det_id ASC', $joinArray, 'd' );
//  			($transfer_det);
 			if (! $transfer_det) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select det fail' );
 			}
 			// 出库明细
 			foreach ( $transfer_det as $det ) {
 				$PRODUCT = ProductDAO::getInstance()->iselect(["price","quantity"], "product_id = :pid", [':pid'=>$det['product_id']],'one');
 				if(isset($PRODUCT['price'])){
 					$price = $PRODUCT['price'];
 				} else {
 					$price = 0;
 				}
 				//
 				if($PRODUCT['quantity'] < $det['base_quantity']){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'quantity overflow');
 				}
 				
 				
 				$WAREHOUSE = WarehouseDAO::getInstance()->iselect("is_scrapped,warehouse_name", "warehouse_id =:wid", [':wid'=>$det['warehouse_in']],'one');
 				// 更新product quantity 减库存 // 如果是报废仓，要减去
 				if(isset($WAREHOUSE['is_scrapped'])){
	 				if($WAREHOUSE['is_scrapped'] == '1'){//报废单
		 				$pro_select = ProductDAO::getInstance ()->updateAllCounters ( [
		 						'quantity' => - $det ['base_quantity'],
		 						'amount' => -($det['base_quantity'] * $price)
		 				], "product_id =:id", [
		 						':id' => $det ['product_id']
		 				] );
		 				if (! $pro_select) {
		 					$tr->rollBack ();
		 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
		 				}
	 				}	
 				} else {
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','select scrapped failed');
 				}
 				
 				//出库单是报废仓，加上quantity
 				$scrap_out = 0;//出库仓是否是报废仓
 				$warehouse_out = WarehouseDAO::getInstance()->iselect("is_scrapped,warehouse_name", "warehouse_id =:wid", [':wid'=>$det['warehouse_out']],'one');
 				if(isset($warehouse_out['is_scrapped'])){
 					if($warehouse_out['is_scrapped'] == '1'){
 						$prod_select = ProductDAO::getInstance ()->updateAllCounters ( [
 								'quantity' =>  $det ['base_quantity'],
 								'amount' => ($det['base_quantity'] * $price)
 						], "product_id =:id", [
 								':id' => $det ['product_id']
 						] );
 						if (! $prod_select) {
 							$tr->rollBack ();
 							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
 						}
 						$scrap_out = 1;
 					}
 				} else {
 					$tr->rollBack();
 					return  $this->handleApiFormat(EnumOther::ACK_FAILURE,'','select scrapped failed');
 				}
 				
 				///transaction
 				$column_trans = [
 						[
 								'goods_id' => $det ['product_id'],
 								'quantity' => $det ['base_quantity'],
 								'quantity_unit' => $det ['base_unit'],
 								'origin_type' => EnumOriginType::origin_transfer,
 								'origin_id' => $det ['transfer_no'],
 								'origin_line_id' => $det ['transfer_det_id'], // 原单序号
 								'origin_time' => $det ['transfer_date'],
 								'init_num' =>$PRODUCT ['quantity'],
 								'warehouse_id' => $det ['warehouse_out'],//调出仓库
 								'flag' => EnumOther::OUT_FLAG,
 						],
 						[
 								'goods_id' => $det ['product_id'],
 								'quantity' => $det ['base_quantity'],
 								'quantity_unit' => $det ['base_unit'],
 								'origin_type' => EnumOriginType::origin_transfer,
 								'origin_id' => $det ['transfer_no'],
 								'origin_line_id' => $det ['transfer_det_id'], // 原单序号
 								'origin_time' => $det ['transfer_date'],
 								'init_num' => $scrap_out ? $PRODUCT['quantity']:($PRODUCT ['quantity'] - $det['base_quantity']), // 上期数量
 								'warehouse_id' => $det ['warehouse_in'],//调入仓库
 								'flag' => EnumOther::IN_FLAG, //
 						]
 				];
 					
 				foreach ($column_trans as $trans){
 					$res_trans = TransactionDAO::getInstance ()->iinsert ($trans, true );
 					if (! $res_trans) {
 						$tr->rollBack ();
 						return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transaction failed' );
 					}
 				}
 				
 				
 				//price_transaction 
 				if($det['transfer_type'] == EnumOriginType::origin_scrapped){//只在报废单写入
	 				$price_trans = [
	 					'product_id' => $det ['product_id'],
	 					'quantity' => $det ['base_quantity'],
	 					'quantity_unit' => $det ['base_unit'],
	 					'price' => $det['base_price'],
	 					'amount' => $det['amount'],
	 					'origin_type' => EnumOriginType::origin_scrapped,
	 					'origin_id' => $det ['transfer_id'],
	 					'origin_no' => $det['transfer_no'],
	 					'origin_line_id' => $det ['transfer_det_id'], // 原单序号
	 					'origin_time' => $det ['transfer_date'],
	 					'warehouse_id' => $det ['warehouse_in'],//调入仓库
	 					'cost_price' => $det['cost_price'],
	 					'cost_amount' => $det['cost_amount'],
	 				];
	 				$price_res = PriceTransactionDAO::getInstance()->iinsert($price_trans, true);
	 				if(! $price_res){
	 					$tr->rollBack();
	 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'save price transaction failed');
	 				}
 				}
 				//---end
 				//product_update_log 商品更新记录
 				$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type,EnumOriginType::origin_transfer);
				$log_columns = [ 
						[ 
								'product_id' => $det ['product_id'],
								'update_num' => $det ['base_quantity'],
								'num_unit' => $det ['base_unit'],
								'origin_id' => $id,
								'origin_no' => $det['transfer_no'],
								'origin_line_id' => $det ['transfer_det_id'],
								'origin_type' => EnumOriginType::origin_transfer,
								'update_time' => strtotime ( date ( 'Y-m-d' ) ),
								'flag' => EnumOther::OUT_FLAG,
								'initial_num' => $PRODUCT ['quantity'], // 上期数量
								'remark' => $_order_type .$warehouse_out['warehouse_name']. EnumOther::MINUS,
								'warehouse_id'=> $det['warehouse_out'],
								'create_man' => Yii::$app->user->id,
						],
						[ 
								'product_id' => $det ['product_id'],
								'update_num' => $det ['base_quantity'],
								'num_unit' => $det ['base_unit'],
								'origin_id' => $id,
								'origin_no' => $det['transfer_no'],
								'origin_line_id' => $det ['transfer_det_id'],
								'origin_type' => EnumOriginType::origin_transfer,
								'update_time' => strtotime ( date ( 'Y-m-d' ) ),
								'flag' => EnumOther::IN_FLAG,
								'initial_num' => $scrap_out ? $PRODUCT['quantity']:($PRODUCT ['quantity'] - $det['base_quantity']), // 上期数量
								'remark' => $_order_type .$WAREHOUSE['warehouse_name']. EnumOther::PLUS, 
								'warehouse_id' => $det['warehouse_in'],
								'create_man' => Yii::$app->user->id,
						]
						 
				];
				
				foreach ($log_columns as $logs){
	 				$res_log = ProductUpdateLogDAO::getInstance()->iinsert($logs, true);
	 				if(! $res_log){
	 					$tr->rollBack();
	 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
	 				}
				}
 				
 				//分仓列表数据的插入或者更新--start
 				//出库
 				$stockout_conditions = "warehouse_id =:wid and product_id=:pid and delete_flag =:flag";
 				$stockout_params = [
 						':wid'=>$det['warehouse_out'],
 						':pid'=>$det['product_id'],
 						':flag'=> EnumOther::NO_DELETE,
 				];
 				$stockout_select = StockPileDAO::getInstance()->iselect("stock_pile_id", $stockout_conditions, $stockout_params,'one');
 				if(! $stockout_select){
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select stock pile failure' );
 				} else {
 					//有数据，更新数据
 					$stockout_update = StockPileDAO::getInstance()->updateAllCounters(['quantity'=> -$det['base_quantity']], $stockout_conditions, $stockout_params);
 					if(! $stockout_update){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','update stock pile failure');
 					}
 				}
 				//入库
 				$stockin_conditions = "warehouse_id =:wid and product_id=:pid and delete_flag =:flag";
 				$stockin_params = [
 						':wid'=>$det['warehouse_in'],
 						':pid'=>$det['product_id'],
 						':flag'=> EnumOther::NO_DELETE,
 				];
 				$stockin_select = StockPileDAO::getInstance()->iselect("stock_pile_id", $stockin_conditions, $stockin_params,'one');
 				if(! $stockin_select){
					$stockin_columns = [
							'warehouse_id'=> $det['warehouse_in'],
							'product_id'=> $det['product_id'],
							'quantity'=> $det['base_quantity'],
							'quantity_unit'=> $det['base_unit'],
					];
					$stockin_insert = StockPileDAO::getInstance()->iinsert($stockin_columns, true);
					if(! $stockin_insert){
						$tr->rollBack ();
						return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'insert stock pile failure' );
					}
					
 				} else {
 					//有数据，更新数据
 					$stockin_update = StockPileDAO::getInstance()->updateAllCounters(['quantity'=> $det['base_quantity']], $stockin_conditions, $stockin_params);
 					if(! $stockin_update){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','update stock pile failure');
 					}
 				}
 				//分仓 --end
 					
 			}
 			$tr->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tr->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
 		}
 	}
 	
 	
 	
 	
 	/**
 	 * @desc 调拨单明细(弹出框)
 	 * @author liaojianwen
 	 * @date 2017-04-05
 	 */
 	public function getTransferDet($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'transfer_det_id',
 				'd.transfer_id',
 				'd.product_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
 		];
 			
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.product_id"
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit"
 				]
 		];
 		$conditions = "d.transfer_id = :id and d.delete_flag = :dflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 		];
 		$result = TransferDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"transfer_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	
 	/**
 	 * @desc 删除调拨单
 	 * @param $ids string // 1,2,3,4
 	 * @author liaojianwen
 	 * @date 2017-04-07
 	 */
 	public function delTransfer($ids)
 	{
 		if(empty($ids)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$_ids = explode ( ',', $ids );
 			
 		$tT = Yii::$app->db->beginTransaction ();
 		try {
 			foreach ( $_ids as $id ) {
 				$res_transfer = TransferDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
 				if(!$res_transfer){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_transfer fail');
 				}
 				//transfer_detail
 				$transfer_det = TransferDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "transfer_id=:id", [':id'=>$id]);
 				if(!$transfer_det){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_transfer_det fail');
 				}
 				//更新product_quantity
 				$fields = [
 						't.goods_id',
 						't.quantity',
 						't.transaction_id',
 						'd.quantity_unit',
 						't.warehouse_id',
 						't.origin_id',
 						't.origin_type',
 						'd.quantity_unit',
 						'd.transfer_det_id',
 						't.flag'
 				];
 				$conditions = "t.delete_flag = :flag";
 				$params = [
 						':flag'=>EnumOther::NO_DELETE,
 				];
 				$joinArray = [
 						[
 								'transfer i',
 								'i.transfer_no = t.origin_id and i.transfer_id = '.$id,
 								'right'=>'',
 						],
 						[
 								'transfer_detail d',
 								'd.transfer_det_id = t.origin_line_id',
 								'left'=>''
 						]
 				];
 				$trans_select = TransactionDAO::getInstance()->iselect($fields, $conditions, $params,'all',"t.create_time ASC",$joinArray,'t');
 				if (! empty ( $trans_select )) {
 					// 已确认的入库单才有transtions,减库存
 					foreach ( $trans_select as $trans ) {
 						//记录更新product 前的quantity
 						$PRODUCT = ProductDAO::getInstance()->iselect("quantity", "product_id = :pid", [':pid'=>$trans['goods_id']],'one');
 						//product 更新数量
 						$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $trans['origin_type']);
 						if($trans['flag']){
 							//transtion 是入库     删除即是减少库存
 							$WAREHOUSE = WarehouseDAO::getInstance()->iselect("is_scrapped,warehouse_name", "warehouse_id =:wid", [':wid'=>$trans['warehouse_id']],'one');
 							//如果入库的仓库是报废仓就不用操作
 							if($WAREHOUSE['is_scrapped'] == '0'){//非报废仓
		 						$pro_minus = ProductDAO::getInstance ()->updateAllCounters ( [
		 								'quantity' => - $trans ['quantity'],
		 						], "product_id =:id", [
		 								':id' => $trans ['goods_id']
		 						] );
		 		
		 						if (! $pro_minus) {
		 							$tr->rollBack ();
		 							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
		 						}
 							}
	 						$log_columns = [
	 								'product_id' => $trans ['goods_id'],
	 								'update_num' => $trans ['quantity'],
	 								'num_unit' => $trans ['quantity_unit'],
	 								'origin_id' => $id,
	 								'origin_no' => $trans['origin_id'],
	 								'origin_line_id' => $trans ['transfer_det_id'],
	 								'origin_type' => $trans ['origin_type'],
	 								'update_time' => strtotime ( date ( 'Y-m-d' ) ),
	 								'flag' => EnumOther::OUT_FLAG,
	 								'initial_num' => $PRODUCT ['quantity'], // 上期数量
	 								'remark' => $_order_type.$WAREHOUSE['warehouse_name'] . EnumOther::MINUS . ',调拨单调入记录删除' ,
	 								'warehouse_id' => $trans['warehouse_id'],
	 								'create_man' => Yii::$app->user->id,
	 						];
	 						
 						} else {
 							$warehouse_out = WarehouseDAO::getInstance()->iselect("is_scrapped,warehouse_name", "warehouse_id =:wid", [':wid'=>$trans['warehouse_id']],'one');
 							if($warehouse_out['is_scrapped'] == '0'){//非报废仓,出库仓是报废仓不能更改product_quantity
	 							$pro_plus = ProductDAO::getInstance ()->updateAllCounters ( [
	 									'quantity' => $trans ['quantity'],
	 							], "product_id =:id", [
	 									':id' => $trans ['goods_id']
	 							] );
	 							
	 							if (! $pro_plus) {
	 								$tr->rollBack ();
	 								return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
	 							}
 							}
 							$log_columns = [
 									'product_id' => $trans ['goods_id'],
 									'update_num' => $trans ['quantity'],
 									'num_unit' => $trans ['quantity_unit'],
 									'origin_id' => $id,
 									'origin_no' => $trans['origin_id'],
 									'origin_line_id' => $trans ['transfer_det_id'],
 									'origin_type' => $trans ['origin_type'],
 									'update_time' => strtotime ( date ( 'Y-m-d' ) ),
 									'flag' => EnumOther::IN_FLAG,
 									'initial_num' => $PRODUCT ['quantity'], // 上期数量
 									'remark' => $_order_type .$warehouse_out['warehouse_name']. EnumOther::PLUS . ',调拨单调出记录删除' ,
 									'warehouse_id' => $trans['warehouse_id'],
 									'create_man' => Yii::$app->user->id,
 							];
 						}	
 						//product_update_log 商品更新记录
//  						$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $trans['origin_type']);
// 						$log_columns = [ 
// 								[ 
// 										'product_id' => $trans ['goods_id'],
// 										'update_num' => $trans ['quantity'],
// 										'num_unit' => $trans ['quantity_unit'],
// 										'origin_id' => $id,
// 										'origin_no' => $trans['origin_id'],
// 										'origin_line_id' => $trans ['transfer_det_id'],
// 										'origin_type' => $trans ['origin_type'],
// 										'update_time' => strtotime ( date ( 'Y-m-d' ) ),
// 										'flag' => EnumOther::IN_FLAG,
// 										'initial_num' => $PRODUCT ['quantity'], // 上期数量
// 										'remark' => $_order_type . EnumOther::PLUS . ',销售出库单删除' ,
// 										'warehouse_id' => $det['warehouse_in']
// 								],
// 								[ 
// 										'product_id' => $trans ['goods_id'],
// 										'update_num' => $trans ['quantity'],
// 										'num_unit' => $trans ['quantity_unit'],
// 										'origin_id' => $id,
// 										'origin_no' => $trans['origin_id'],
// 										'origin_line_id' => $det ['transfer_det_id'],
// 										'origin_type' => EnumOriginType::origin_transfer,
// 										'update_time' => strtotime ( date ( 'Y-m-d' ) ),
// 										'flag' => EnumOther::IN_FLAG,
// 										'initial_num' => $PRODUCT ['quantity'], // 上期数量
// 										'remark' => $_order_type . EnumOther::PLUS,
// 										'warehouse_id' => $det['warehouse_in']
// 								]

								 
// 						];
 						$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 						if(! $res_log){
 							$tr->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 						}
 							
 						//删除transaction 数据
 						$columns = [
 								'delete_flag'=>EnumOther::DELETED,
 						];
 						$conditions = "transaction_id = :tid";
 						$params = [
 								':tid'=>$trans['transaction_id'],
 						];
 						$trans_update = TransactionDAO::getInstance()->iupdate($columns, $conditions, $params);
 							
 						if(empty($trans_update)){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','tansaction del fail');
 						}
 						// 更新stock_file 分仓表信息
 						if($trans['flag']){
 							//调入仓库  删除就要减去 quantity
	 						$stock_minus = StockPileDAO::getInstance ()->updateAllCounters ( [
	 								'quantity' => - $trans ['quantity']
	 						], "warehouse_id =:wid and product_id=:pid and delete_flag =:flag", [
	 								':wid' => $trans ['warehouse_id'],
	 								':pid' => $trans ['goods_id'],
	 								':flag' => EnumOther::NO_DELETE
	 						] );
	 						if(! $stock_minus){
	 							$tr->rollBack ();
	 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile quantity failure');
	 						}
 						} else {
 							$stock_plus = StockPileDAO::getInstance ()->updateAllCounters ( [
 									'quantity' => $trans ['quantity']
 							], "warehouse_id =:wid and product_id=:pid and delete_flag =:flag", [
 									':wid' => $trans ['warehouse_id'],
 									':pid' => $trans ['goods_id'],
 									':flag' => EnumOther::NO_DELETE
 							] );
 							if(! $stock_plus){
 								$tr->rollBack ();
 								return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile quantity failure');
 							}
 						}
 					}
 				}
 			}
 				
 			$tT->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tT->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 获取调拨单列表数据
 	 * @author liaojianwen
 	 * @date 2017-04-01
 	 */
 	public function getTransferStatistics ( $pageInfo = [], $condition, $filter = null)
 	{
//  		if(empty($pageInfo)){
//  			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
//  		}
 		$result = TransferDAO::getInstance()->getTransferStatistics($condition, $filter, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 导出调拨统计信息于execl
 	 * @author liaojianwen
 	 * @date 2017-12-14
 	 */
 	public function exportTransferStatistics($dataInfo,$fileName,$title, $excVer = "xls")
 	{
//  		dd($dataInfo);
 		$data = $dataInfo['list'];
 		$objPHPExecl = new \PHPExcel();
 		$objSheet = $objPHPExecl->getActiveSheet()->setTitle('调拨统计');
 		$objWriter = NULL;
 		// 创建文件格式写入对象实例
 		switch ($excVer){
 			case 'xlsx':
 				$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExecl);
 				break;
 			case 'xls':
 				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
 				break;
 			default:
 				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
 		}
 		//设置宽度
 		$objSheet->mergeCells("A1:G2");
 		$objSheet->setCellValue("A1", $title);
 		$objSheet->getStyle('A1')->getFont()->setSize(26);
 		$objSheet->getStyle('A1')->getFont()->setBold(true);
 		$objSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 		
 		$objSheet->getColumnDimension('A')->setWidth(20);
 		$objSheet->getColumnDimension('B')->setWidth(20);
 		$objSheet->getColumnDimension('C')->setWidth(20);
 		$objSheet->getColumnDimension('D')->setWidth(20);
 		$objSheet->getColumnDimension('E')->setWidth(30);
 		$objSheet->getColumnDimension('F')->setWidth(20);
 		$objSheet->getColumnDimension('G')->setWidth(20);
 		$objSheet->setCellValue('A3', '调拨开始日期');
 		$objSheet->getStyle('A3')->getFont()->setBold(true);
 		$objSheet->setCellValue('B3', '调拨截至日期');
 		$objSheet->getStyle('B3')->getFont()->setBold(true);
 		$objSheet->setCellValue('C3', '调出仓库');
 		$objSheet->getStyle('C3')->getFont()->setBold(true);
 		$objSheet->setCellValue('D3', '调入仓库');
 		$objSheet->getStyle('D3')->getFont()->setBold(true);
 		$objSheet->setCellValue('E3', '商品');
 		$objSheet->getStyle('E3')->getFont()->setBold(true);
 		$objSheet->setCellValue('F3', '数量');
 		$objSheet->getStyle('F3')->getFont()->setBold(true);
 		$objSheet->setCellValue('G3', '单位');
 		$objSheet->getStyle('G3')->getFont()->setBold(true);
 		
 		$i = 'A';
		for($n = 0; $n < 8; $n ++) {
			$count = $i ++;
			$objSheet->getStyle ( $count . '3' )->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		}
 	
 		$rowNum = 4;
 		$total_quantity = 0;
 		foreach($data as $det){
 			$total_quantity += $det['quantity'];
 			$this->_genExcelFont($objSheet, "A".$rowNum, "A".$rowNum, $dataInfo['starTime'], false);
 			$this->_genExcelFont($objSheet, "B".$rowNum, "B".$rowNum, $dataInfo['endTime'], false);
 			$this->_genExcelFont($objSheet, "C".$rowNum, "C".$rowNum, $det['warehouse_out_name'], false);
 			$this->_genExcelFont($objSheet, "D".$rowNum, "D".$rowNum, $det['warehouse_in_name'], false);
 			$this->_genExcelFont($objSheet, "E".$rowNum, "E".$rowNum, $det['product_name'], false);
 			$this->_genExcelFont($objSheet, "F".$rowNum, "F".$rowNum, $det['quantity'], false);
 			$this->_genExcelFont($objSheet, "G".$rowNum, "G".$rowNum, $det['unit_name'], false);
 			
 			$rowNum++;
 		}
 		$this->_genExcelFont($objSheet, "F".$rowNum, "F".$rowNum, $total_quantity, false);
 		
 		ob_end_clean(); // 去掉缓存
 		header("Content-Type: application/force-download");
 		header("Content-Type: application/octet-stream");
 		header("Content-Type: application/download");
 		header('Content-Disposition:inline;filename="' . $fileName . '.xls"');
 		header("Content-Transfer-Encoding: binary");
 		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 		header("Pragma: no-cache");
 		//  		            $objWriter->save("upload/demo.xlsx");
 		$objWriter->save('php://output');
 	}

	/**
	 * @desc 调拨单明细
	 * @author liaojianwen
	 * @date 2017-09-27
	 */
	public function getExportTransfer($cond, $pageInfo, $filter)
	{
		if(empty($cond)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'param is empty');
		}
		$result = TransferDAO::getInstance()->getExportTransfer($cond, $pageInfo, $filter);
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
		}
		
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
		
	}
	
	/**
	 * @desc 导出的调拨单明细
	 * @author liaojianwen
	 * @date 2017-09-28
	 */
	public function getExproInfo($condition)
	{
		if(empty($condition)){
			return false;
		}
		$result = TransferDAO::getInstance()->getExproInfo($condition);
		if(!$result)
			return false;
		return  $result;
	}

	/**
	 * @desc 导出调拨单商品
	 * @author liaojianwen
	 * @date 2017-09-28
	 */
	public function exportProInfo($proInfo, $filename, $title, $excVer = "xls")
	{
		$data = $proInfo;
		$objPHPExecl = new \PHPExcel();
		$objSheet = $objPHPExecl->getActiveSheet();
		$objWriter = NULL;
		// 创建文件格式写入对象实例
		switch ($excVer){
			case 'xlsx':
				$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExecl);
				break;
			case 'xls':
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
				break;
			default:
				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
		}
		//设置宽度
		$objSheet->mergeCells("A1:G1");
		$objSheet->setCellValue("A1", $title);
		$objSheet->getStyle('A1')->getFont()->setBold(true);
		$objSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		
		$objSheet->getColumnDimension('A')->setWidth(12);
		$objSheet->getColumnDimension('B')->setWidth(40);
		$objSheet->getColumnDimension('g')->setWidth(30);
		
		$objSheet->setCellValue('G2', '单位：元');
		
		$objSheet->setCellValue('A3', '报损日期');
		$objSheet->setCellValue('B3', '商品名称');
		$objSheet->setCellValue('C3', '单位');
		$objSheet->setCellValue('D3', '数量');
		$objSheet->setCellValue('E3', '进价');
		$objSheet->setCellValue('F3', '总价');
		$objSheet->setCellValue('G3', '备注');
		
		$rowNum = 4;
		foreach($data as $det){
			$this->_genExcelFont($objSheet, "A".$rowNum, "A".$rowNum, date('n月j日', $det['transfer_date']+8*3600), false);
			$this->_genExcelFont($objSheet, "B".$rowNum, "B".$rowNum, $det['product_name'], false);
			$this->_genExcelFont($objSheet, "C".$rowNum, "C".$rowNum, $det['unit_name'], false);
			$this->_genExcelFont($objSheet, "D".$rowNum, "D".$rowNum, $det['base_quantity'], false);
			$this->_genExcelFont($objSheet, "E".$rowNum, "E".$rowNum, $det['price'], false);
			$this->_genExcelFont($objSheet, "F".$rowNum, "F".$rowNum, $det['base_quantity']*$det['price'], false);
			$this->_genExcelFont($objSheet, "G".$rowNum, "G".$rowNum, $det['remark'], false);
		
			$rowNum++;
		}
		$this->_genExcelFont($objSheet, "F".$rowNum, "F".$rowNum, "=SUM(F4:F".$rowNum.")", false);
			
		ob_end_clean(); // 去掉缓存
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");
		header('Content-Disposition:inline;filename="' . $filename . '.xls"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Pragma: no-cache");
		$objWriter->save('php://output');
	}
}